//
//  BooKViewController.m
//  Reader
//
//  Created by ZF on 16/12/11.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "BooKViewController.h"
#import "TextViewController.h"

@interface BooKViewController ()<UIPageViewControllerDelegate,UIPageViewControllerDataSource>
{
    CGFloat totalHeight;
    CGFloat totalPages;
    
    NSInteger currentPage;
    NSInteger worldNumber;
    
    NSString *content;
    NSInteger index;//index = currentPage 用于保存当前页数，直到翻页完成再次赋值
    
    BOOL toolisHide;
    BOOL atNight;
 
    UIColor *backColor;
    UIView  *navigationView;
    UIView *toolView;
    UIView *fontSetToolView;
}

@property (strong, nonatomic) UIPageViewController *pageVCon;

@end


@implementation BooKViewController

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadTEXT];
   
    toolisHide = YES;
    atNight = NO;
  
    
    backColor = [UIColor whiteColor];
    
    //计算绘制文本需要多少size
    CGRect rct = [content boundingRectWithSize:CGSizeMake(self.view.frame.size.height, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:25.0]} context:nil];
    NSLog(@"Total height:%lf",rct.size.height);
    
    totalPages = ceil(rct.size.height / self.view.frame.size.height);//ceil()如果是小数求最大数
    
    NSLog(@"Total Page:%lf",totalPages);
    
    worldNumber = content.length / totalPages;
    NSLog(@"每页字数:%ld",worldNumber);

    
    currentPage = 0;
    index = currentPage;
    
    TextViewController *textVC = [self getCurrentViewController];
    [self.pageVCon setViewControllers:@[textVC] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
    
    [self addChildViewController:self.pageVCon];
    [self.view addSubview:self.pageVCon.view];
    
    
    navigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    navigationView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
   
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(10, 2, 80, 60);
    
    NSMutableAttributedString *attributStr = [[NSMutableAttributedString alloc] initWithString:@"<Reader"];
    [attributStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, 1)];
    [attributStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(1, 1)];
    [attributStr addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(2, 1)];
    [attributStr addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(3, 1)];
    [attributStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(4, 1)];
    [attributStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(5, 1)];
    [attributStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:66/255.0 green:51/255.0 blue:203/255. alpha:1.0]range:NSMakeRange(6, 1)];
    [backBtn setAttributedTitle:attributStr forState:UIControlStateNormal];
    backBtn.titleLabel.textAlignment =  NSTextAlignmentLeft ;
    
    attributStr = [[NSMutableAttributedString alloc] initWithString:@"<Reader"];
    [attributStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, attributStr.string.length)];
    [backBtn setAttributedTitle:attributStr forState:UIControlStateHighlighted];
    
    backBtn.titleLabel.font = [UIFont systemFontOfSize:20];
    [backBtn addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    [navigationView addSubview:backBtn];
    
    
    //button in the toolView
    toolView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 60, self.view.frame.size.width, 60)];
    toolView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
  
    UIButton *nightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nightBtn.tag = 700;
    nightBtn.frame = CGRectMake(10, 10, 40, 40);
    [nightBtn setImage:[UIImage imageNamed:@"夜间模式"] forState:UIControlStateNormal];
    [nightBtn addTarget:self action:@selector(theNight:) forControlEvents:UIControlEventTouchUpInside];
    [toolView addSubview:nightBtn];
    
    
    UIButton *fontSet = [UIButton buttonWithType:UIButtonTypeCustom];
    fontSet.frame = CGRectMake(70, 10, 40, 40);
    [fontSet setImage:[UIImage imageNamed:@"字体"] forState:UIControlStateNormal];
    [fontSet addTarget:self action:@selector(fontSet) forControlEvents:UIControlEventTouchUpInside];
    [toolView addSubview:fontSet];
    
    
    //button in the fontSetToolView
    fontSetToolView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 120, self.view.frame.size.width, 120)];
    fontSetToolView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
    
    NSArray<UIColor *> *colorArr = [NSArray arrayWithObjects:[UIColor colorWithRed:185/255.0 green:251/255.0 blue:136/255.0 alpha:1.0],[UIColor colorWithRed:234/255.0 green:234/255.0 blue:160/255.0 alpha:1.0] ,[UIColor colorWithRed:204/255.0 green:116/255.0 blue:19/255.0 alpha:1.0], [UIColor whiteColor],nil];
    for(int i = 0; i < 4; i++)
    {
        UIButton *colorBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        colorBtn1.frame = CGRectMake(10 + 60 * i, fontSetToolView.frame.size.height - 50, 40, 40);
        colorBtn1.backgroundColor = colorArr[i];
        colorBtn1.layer.cornerRadius = 20.0;
        colorBtn1.tag = 800 + i;
        [colorBtn1 addTarget:self action:@selector(backgroundColorFromColorButton:) forControlEvents:UIControlEventTouchUpInside];
        [fontSetToolView addSubview:colorBtn1];
    }
    
    //Gesture
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap)];
    [self.pageVCon.view addGestureRecognizer:tapGesture];
}

- (void)backgroundColorFromColorButton:(UIButton *)sender
{
    UIButton *btn = [fontSetToolView viewWithTag:800];
     UIButton *btn1 = [fontSetToolView viewWithTag:801];
     UIButton *btn2 = [fontSetToolView viewWithTag:802];
     UIButton *btn3 = [fontSetToolView viewWithTag:803];
    NSArray *buttonArr = [NSArray arrayWithObjects:btn, btn1, btn2, btn3, nil];
    
    sender.layer.borderWidth = 2.0;
    sender.layer.borderColor = [UIColor redColor].CGColor;
    [sender setImage:[UIImage imageNamed:@"灯泡"] forState:UIControlStateNormal];
    
    for(UIButton *button in buttonArr)
    {
        if(button.tag != sender.tag)
        {
            button.layer.borderWidth = 0.0;
            [button setImage:nil forState:UIControlStateNormal];
        }
    }
    
    if(atNight)
    {
        atNight = NO;
        UIButton *button1 = [toolView viewWithTag:700];
        [button1 setImage:[UIImage imageNamed:@"夜间模式"] forState:UIControlStateNormal];
    }
    
    backColor = sender.backgroundColor;
    [self setPageViewController];
}

//fontSet
- (void)fontSet
{
    [toolView removeFromSuperview];
    [self.view addSubview:fontSetToolView];
}

//返回
- (void)onBack
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//夜间模式按钮
- (void)theNight:(UIButton *)sender
{
    if(!atNight)
    {
        atNight = YES;
        for(int i = 0; i < 4; i++)
        {
            UIButton *button = [fontSetToolView viewWithTag:800 + i];
            [button setImage:nil forState:UIControlStateNormal];
            button.layer.borderWidth = 0.0;
        }
        [sender setImage:[UIImage imageNamed:@"普通模式"] forState:UIControlStateNormal];
        backColor = [UIColor colorWithRed:26/255.0 green:48/255.0 blue:104/255.0 alpha:1.0];
        [self setPageViewController];
    }
    else{
        atNight = NO;
        [sender setImage:[UIImage imageNamed:@"夜间模式"] forState:UIControlStateNormal];
        backColor = [UIColor whiteColor];
        [self setPageViewController];
    }
    
}

//点击手势弹出导航栏，工具栏
- (void)onTap
{
    if(toolisHide)
    {
        [self.view addSubview:navigationView];
        [self.view addSubview:toolView];
        toolisHide = NO;
    }
    else{
        [fontSetToolView removeFromSuperview];
        [navigationView removeFromSuperview];
        [toolView removeFromSuperview];
        toolisHide = YES;
    }
}


//加载书籍数据
- (void)loadTEXT
{
    content = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:[_bookName componentsSeparatedByString:@"."].firstObject withExtension:@".txt"] encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",content);
}



- (void)setPageViewController
{
    TextViewController *textVC = [self getCurrentViewController];
    [self.pageVCon setViewControllers:@[textVC] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
}


- (TextViewController *)getCurrentViewController
{
    TextViewController *textVC = [TextViewController new];
    textVC.backGroudColor = backColor;
    textVC.text = [content substringWithRange:NSMakeRange(worldNumber * currentPage, worldNumber)];
    return textVC;
}


- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    if(currentPage >= totalPages - 1)
    {
        return nil;
    }
    currentPage++;
   
    
    return [self getCurrentViewController];
;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    if(currentPage <= 0)
    {
        return nil;
    }
    currentPage--;
 
    
    return [self getCurrentViewController];

}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed
{
    if(completed)
    {
        index = currentPage;
    }
    else{
        currentPage = index;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (UIPageViewController *)pageVCon
{
    if(!_pageVCon)
    {
        NSDictionary *option = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:UIPageViewControllerSpineLocationMin] forKey:UIPageViewControllerOptionSpineLocationKey];
    
        _pageVCon = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:option];
    
        _pageVCon.dataSource = self;
        _pageVCon.delegate = self;
        
    }
     return _pageVCon;
}

@end
